package com.zysc.processflow.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zysc.processflow.common.util.HttpUtils;
import com.zysc.processflow.common.util.StringUtils;
import com.zysc.processflow.entity.*;
import com.zysc.processflow.mapper.HandletaskMapper;
import com.zysc.processflow.service.*;
import com.zysc.processflow.common.base.BaseService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import java.util.*;

/**
 * <p>
 * 处置任务表 服务实现类
 * </p>
 *
 * @author 正元智慧城市_
 * @since 2022-11-23
 */
@Service
public class HandletaskServiceImpl extends BaseService<HandletaskMapper, Handletask> implements IHandletaskService {

    @Autowired
    IHandleprocessnodeService handleprocessnodeService;
    @Autowired
    IHandleprocesslineService handleprocesslineService;
    @Autowired
    IHandlerecordcurrentnodeService handlerecordcurrentnodeService;
    @Autowired
    IPersonService personService;
    @Autowired
    IOrganizationService organizationService;
    @Autowired
    IHandleprocessccService handleprocessccService;
    @Autowired
    StringUtils stringUtils;


    @Override
    public Boolean removeOldTask(String recordid, String nodeid) {
        Boolean b1 = true;
        LambdaQueryWrapper<Handletask> handletaskqw = new LambdaQueryWrapper<>();
        handletaskqw.eq(Handletask::getRecordid,recordid).eq(Handletask::getNodeid,nodeid);
        List<Handletask> list = this.list(handletaskqw);
        if(list.size()>0){
            b1 = this.remove(handletaskqw);
        }
        return b1;
    }
    @Override
    public Boolean removeOldTaskByNodeList(String recordid, List<String> nodeids) {
        Boolean b1 = true;
        if(nodeids==null||nodeids.size()==0){
            return false;
        }
        LambdaQueryWrapper<Handletask> handletaskqw = new LambdaQueryWrapper<>();
        handletaskqw.eq(Handletask::getRecordid,recordid).in(Handletask::getNodeid,nodeids);
        List<Handletask> list = this.list(handletaskqw);
        if(list.size()>0){
            b1 = this.remove(handletaskqw);
        }
        return b1;
    }
    @Override
    public Boolean removeHandelAndUrgeTaskByRecordId(String recordid) {
        Boolean b1 = true;
        LambdaQueryWrapper<Handletask> handletaskqw = new LambdaQueryWrapper<>();
        List<String> taskTypeList = new ArrayList<>();
        taskTypeList.add("处置任务");
        taskTypeList.add("督办任务");
        handletaskqw.eq(Handletask::getRecordid,recordid).in(Handletask::getType,taskTypeList);
        List<Handletask> list = this.list(handletaskqw);
        if(list.size()>0){
            b1 = this.remove(handletaskqw);
        }
        return b1;
    }

    @Override
    public Boolean saveNodeTaskByRecordAndNextNode(Handlerecord record, Handleprocessnode nextnode) {
        String type = nextnode.getType();
        String needsendmsg = nextnode.getNeedsendmsg();
        Handletask tempTask = new Handletask();
        tempTask.setRecordid(record.getId());
        tempTask.setNodeid(nextnode.getId());
        tempTask.setType("处置任务");

        List<Handletask> tasks = new ArrayList<>();
        List<Person> sendMsgPhoneList = new ArrayList<>();//发短信的电话号集合
        if(type != null && "per".equals(type)){
            String personId = nextnode.getDisposerid();
            String personName = nextnode.getDisposername();
            Person person = personService.getById(personId);
            if(person==null){
                //throw new RuntimeException("未查询到处置人员的信息，请检查！");
            }
            Handletask task = new Handletask();
            BeanUtils.copyProperties(tempTask,task);
            task.setPersonid(personId);
            task.setPersonname(personName);
            tasks.add(task);

            sendMsgPhoneList.add(person);
        }
        if(type != null && "org".equals(type)){
            String orgid = nextnode.getOrgid();
            //1.查詢該單位下所有的人
            List<Person> personList = personService.getPersonListByOrgId(orgid);
            if(personList.size()==0){
                //throw new RuntimeException("之后的一步审核环节,配置的是单位,但未从该单位匹配到人员,请检查!");
            }
            //2.给所有人增加任务
            for(Person person:personList){
                Handletask task = new Handletask();
                BeanUtils.copyProperties(tempTask,task);
                task.setPersonid(person.getId());
                task.setPersonname(person.getName());
                tasks.add(task);
                sendMsgPhoneList.add(person);
            }
        }
        if(type != null && "role".equals(type)){
            //1.获取orgid和roleId
            //String orgid = alarmsService.getById(record.getAlarmid()).getEnterprisecode();
            //1.1 优先取node表里配置的orgId
            String orgId = nextnode.getOrgid();
            //1.2如果没有,那么取报警表里的orgId
            if(StringUtils.isNull(orgId)){
                orgId = record.getOrgid();
            }
            String roleId = nextnode.getRoleid();

            //2.查询该单位下所有此角色的人
            List<Person> personList = personService.getPersonListByOrgIdAndRoleId(orgId,roleId);
            //3.给所有人增加任务
            for(Person person:personList){
                Handletask task = new Handletask();
                BeanUtils.copyProperties(tempTask,task);
                task.setPersonid(person.getId());
                task.setPersonname(person.getName());
                tasks.add(task);
                sendMsgPhoneList.add(person);
            }
        }
        if(type != null && "custom".equals(type)){
            //接口示例:
//            @PostMapping("getTestPersons")
//            @ApiOperation("获取测试人员列表")
//            public ResultBody GetTestPersons(@RequestBody Map<String,Object> map) {
//                String recordid = (String) map.get("recordid");
//                String ywxtid = (String) map.get("ywxtid");
//
//                Map per1 = new HashMap();
//                per1.put("id", "1");
//
//                Map per2 = new HashMap();
//                per2.put("id", "2");
//                per2.put("name", "name2");
//
//                List<Map> list = new ArrayList<>();
//                list.add(per1);
//                list.add(per2);
//
//                return ResultBody.Success(list);
//            }
            //1.1 取出获取人员自定义接口
            String customFunc = nextnode.getCustom();
            //2.组参
            Map map = new HashMap();
            map.put("recordid",record.getId());
            map.put("ywxtid",record.getYwxtid());
            String res = HttpUtils.doPostJson(customFunc, JSON.toJSONString(map));
            JSONObject jsonObject = JSON.parseObject(res);
            Map result = (Map)jsonObject;
            if((Integer) result.getOrDefault("code",500)==200){
                List<Map> persons = (List<Map>)result.get("data");
                for(Map person:persons){
                    String personId = (String)person.get("id");
                    Person per = personService.getById(personId);
                    if(per!=null){
                        Handletask task = new Handletask();
                        BeanUtils.copyProperties(tempTask,task);
                        task.setPersonid(per.getId());
                        task.setPersonname(per.getName());
                        tasks.add(task);
                        sendMsgPhoneList.add(per);
                    }
                }
            }
        }

        boolean result = true;
        if(tasks.size()>0){
            result = this.saveBatch(tasks);
        }else{
            //把上一节点改成阻塞,阻塞原因是nothashandleperson
            LambdaQueryWrapper<Handlerecordcurrentnode> currentnodeQW = new LambdaQueryWrapper<>();
            currentnodeQW.eq(Handlerecordcurrentnode::getCurrentnodeid,nextnode.getId());
            List<Handlerecordcurrentnode> currentnodeList = handlerecordcurrentnodeService.list(currentnodeQW);
            if(currentnodeList.size()>0){
                Handlerecordcurrentnode currentNode = currentnodeList.get(0);
                Handlerecordcurrentnode handlerecordcurrentnode = new Handlerecordcurrentnode();
                handlerecordcurrentnode.setId(currentNode.getId());
                handlerecordcurrentnode.setState("block");
                handlerecordcurrentnode.setBlockreason("nothashandleperson");
                handlerecordcurrentnodeService.saveOrUpdate(handlerecordcurrentnode);
            }
            //把
            return true;
        }
        //4.发送短信
        if(StringUtils.equalsAndNotNull(needsendmsg,"1")){
//            sendMsgPhoneList.stream().forEach(person->{
//                if(!StringUtils.isNull(person.getPhone())){//如果人员连手机号也没有,那不用麻烦了
//                    //1.获取处置短链接
//                    String tempUrl = approvalBYLink + "?userid=" + person.getId() + "&alarmid=" + alarm.getId();//处置h5界面
//                    //String tempUrl = detailByLink + "?alarmid=" + alarm.getId();//详情h5界面
//                    String shortLinkUrl = stringUtils.getShortLinkUrl(tempUrl);
//                    //2.拼接短信模板
//                    String message = "";
//                    try{
//                        //2.1拼接短信模板-组合数据
//                        Map<String, Object> replaceMap = alarm.getMapByInfo();
//                        replaceMap.put("personname",person.getName());
//                        replaceMap.put("url",shortLinkUrl);
//                        if(!StringUtils.isNull(person.getOrgname())){
//                            replaceMap.put("orgname",person.getOrgname());
//                        }
//                        //2.2拼接短信模板-取出模板
//                        String smsModel = analysismodelService.getSmsModelWhenHappened(alarm.getType());
//                        //2.3拼接短信模板-获取最终短信内容
//                        message = StringUtils.replaceVar(replaceMap, smsModel);
//                        if(StringUtils.isNull(message)){
//                            throw new RuntimeException("");
//                        }
//                    }catch(Exception e){
//                        logger.info("报警处置组装短信模板失败,"+alarm);
//                        message = "你好，"+person.getName()+"，"+alarm.getEnterprisename()+"收到一条报警处置信息,详情请登录事件中心系统查看";
//                    }
//                    String finalMessage = message;
//                    try{
//                        if(!StringUtils.isNull(person.getPhone())){
//                            smsUtils.sendMsg(person.getPhone(),finalMessage,person.getName(),alarm.getId(),"alarms","处置人");
//                        }
//                    }catch(Exception e){
//                    }
//                    //});
//                }
//            });
        }
        return result;
    }
}
